package org.example.Hashtable;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Sum_of_Four_Numbers {
    public static void main(String[] args) {
        //四数之和

        //给你一个由 n 个整数组成的数组 nums ，和一个目标值 target 。请你找出并返回满足下述全部条件且不重复的四元组 [nums[a], nums[b], nums[c], nums[d]] （若两个四元组元素一一对应，则认为两个四元组重复）：
        //0 <= a, b, c, d < n
        //a、b、c 和 d 互不相同
        //nums[a] + nums[b] + nums[c] + nums[d] == target
        //你可以按 任意顺序 返回答案 。

        int[] nums = {1,-2,-5,-4,-3,3,3,5};
        int target = -11;
        List<List<Integer>> arrayList = function1(nums, target);
        for (List<Integer> list : arrayList) {
            for (Integer i : list) {
                System.out.print(i+" ");
            }
            System.out.println();
        }
    }

    public static List<List<Integer>> function1(int[] nums,int target){
        Arrays.sort(nums);
        ArrayList<List<Integer>> arrayList = new ArrayList<>();
        for (int i = 0; i < nums.length; i++) {
            if (nums[i]>0 && nums[i]>target){
                return arrayList;
            }
            if (i !=0 && nums[i-1]==nums[i]){
                continue;
            }
            for (int j = i+1; j < nums.length; j++) {
                long sun12 = (long)nums[i] + nums[j];
                if (j !=i+1 && nums[j-1]==nums[j]){
                    continue;
                }
                int left = j+1;
                int right = nums.length-1;
                while (left < right){
                    if (sun12+nums[left]+nums[right]==target){
                        ArrayList<Integer> list = new ArrayList<>();
                        list.add(nums[i]);
                        list.add(nums[j]);
                        list.add(nums[left]);
                        list.add(nums[right]);
                        arrayList.add(list);
                        while (left < right && nums[left] == nums[left+1]){
                            left++;
                        }
                        while (left < right && nums[right-1] == nums[right]){
                            right--;
                        }
                        left++;
                        right--;
                    } else if (sun12 + nums[left] + nums[right] < target) {
                        left++;
                    }else {
                        right--;
                    }
                }
            }
        }
        return arrayList;
    }
}
